import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_news.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/page/mine/new/question_details_page.dart';
import 'package:flutter_learn_vi/src/page/news/news_detaile_page.dart';
import 'package:flutter_learn_vi/src/utils/date_utils.dart';
import 'package:flutter_learn_vi/src/utils/navigator_utils.dart';
import 'package:get/get.dart';

import '../../topic/topic_details_page.dart';
import '../../topic/topic_enum.dart';
import 'controller/my_collect_controller.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/13.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
/// 我的收藏
class MyCollectPage extends StatefulWidget {
  @override
  _MyCollectPageState createState() => _MyCollectPageState();
}

class _MyCollectPageState extends State<MyCollectPage>
    with SingleTickerProviderStateMixin {
  @override
  void initState() {
    super.initState();

    Get.put(MyCollectController());
    _tabController = new TabController(length: 3, vsync: this);
    Future.delayed(Duration.zero, () {
      Get.find<MyCollectController>().onRefresh(index: 0);
    });
  }

  TabController _tabController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("我的收藏"),
        bottom: TabBar(
          indicatorColor: Colors.red,
          controller: _tabController,
          onTap: (int index) {
            Get.find<MyCollectController>().onRefresh(index: index);
          },
          tabs: [
            Tab(text: '全部'),
            Tab(text: '新闻'),
            Tab(text: '学习'),
          ],
        ),
        actions: [
          TextButton(
              onPressed: () {
                NavigatorUtils.pushPage(
                  context,
                  TopicDetilsPage(
                    categoryOne: "",
                    categoryTwo: "",
                    examType: "N",
                    pageTitle: "我的收藏题练习",
                    topicEnum: TopicEnum.muyCollect,
                  ),
                );
              },
              child: Text("收藏题练习"))
        ],
      ),
      backgroundColor: Colors.white,

      ///填充布局
      body: RefreshIndicator(
        onRefresh: () async {
          Get.find<MyCollectController>().onPullRefresh();
          return true;
        },
        child: GetBuilder(
          builder: (MyCollectController controller) {
            return buildAnimatedSwitcher(context, controller);
          },
        ),
      ),
    );
  }

  ///AnimatedSwitcher 的基本使用
  AnimatedSwitcher buildAnimatedSwitcher(
      BuildContext context, MyCollectController controller) {
    return AnimatedSwitcher(
      //动画执行切换时间
      duration: const Duration(milliseconds: 400),

      //动画构建器 构建指定动画类型
      transitionBuilder: (Widget child, Animation<double> animation) {
        //执行缩放动画
        return FadeTransition(child: child, opacity: animation);
      },
      //执行动画的子 Widget
      //只有子 Widget 被切换时才会触发动画
      child: buildListView(controller),
    );
  }

  Widget buildListView(MyCollectController controller) {
    if (controller.isLoading) {
      return Center(
        child: LoadingWidget(),
      );
    }
    if (controller.newsList.length == 0) {
      return Center(
        child: NoDataWidget(
          text: "暂无收藏内容",
        ),
      );
    }
    return ListView.builder(
      //去除内边距
      padding: EdgeInsets.all(0),
      //列表子Item个数
      itemCount: controller.newsList.length,
      //每个子Item的布局构建
      itemBuilder: (BuildContext context, int index) {
        return buildBodyWidget(index, controller);
      },
    );
  }

  //每个子Item的布局构建
  Widget buildBodyWidget(int index, MyCollectController controller) {
    NewsBean newsBean = controller.newsList[index];

    //水波纹点击事件监听
    return InkWell(
      onLongPress: () async {
        bool isSelect = await showCupertinoDialog(
            builder: (BuildContext context) {
              return CupertinoAlertDialog(
                title: Text("温馨提示"),
                content: Container(
                  padding: EdgeInsets.all(10),
                  child: Text("确定取消收藏吗？"),
                ),
                actions: [
                  CupertinoDialogAction(
                    child: Text("取消"),
                    onPressed: () {
                      NavigatorUtils.pop(context, parameters: false);
                    },
                  ),
                  CupertinoDialogAction(
                    child: Text("确定"),
                    onPressed: () {
                      NavigatorUtils.pop(context, parameters: true);
                    },
                  )
                ],
              );
            },
            context: context);

        if (isSelect != null && isSelect) {
          Get.find<MyCollectController>()
              .cancleCollectFunction(newsBean.collectId);
        }
      },
      //手指点击抬起时的回调
      onTap: () {
        if (newsBean.collectType == "news") {
          //打开新的页面
          NavigatorUtils.pushPage(
            context,
            NewsDetailePage(
              newsId: newsBean.id,
              screenSize: MediaQuery.of(context).size,
            ),
          );
        } else {
          NavigatorUtils.pushPage(
            context,
            QusetionDetailsPage(
              id: newsBean.id,
            ),
          );
        }
        //showWebViewPage(context: context, pageUrl: newsBean.detailUrl);
      },
      child: Container(
        margin: EdgeInsets.only(top: 1),
        padding: EdgeInsets.all(10),
        color: Colors.white,
        //线性布局左右排列
        child: Row(
          //主轴方向开始对齐 在这里是左对齐
          mainAxisAlignment: MainAxisAlignment.start,
          //交叉轴上开始对齐 在这里是顶部对齐
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //左侧的图片
            buildLeftImage(newsBean),
            //右侧的文本区域
            buildRightTextArea(index, newsBean)
          ],
        ),
      ),
    );
  }

  ///左侧的图片区域
  Container buildLeftImage(NewsBean newsBean) {
    double radius = 2;

    String url = newsBean.bannerImgUrl;
    if (url == null) {
      url = newsBean.coverImgUrl;
    }
    return Container(
      margin: EdgeInsets.only(right: 6, top: 4),
      child: ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(radius)),
        child: Container(
          padding: EdgeInsets.only(left: 2, right: 2, top: 2, bottom: 2),
          color: newsBean.collectType == "news" ? Colors.red : Colors.blue,
          child: Text(
            "${newsBean.collectType == "news" ? "资讯" : "学习题"}",
            style: TextStyle(color: Colors.white, fontSize: 8),
          ),
        ),
      ),
    );
  }

  ///右侧的文本区域
  Expanded buildRightTextArea(int index, NewsBean newsBean) {
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            "${newsBean.title}",
            softWrap: true,
            overflow: TextOverflow.ellipsis,
            maxLines: 3,
            style: TextStyle(fontSize: 16),
          ),
          SizedBox(height: 4),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Expanded(child: SizedBox()),
              Text(
                "收藏于 ${ViDateUtils.formatDateStr(
                  newsBean.createTime,
                )}",
                softWrap: true,
                overflow: TextOverflow.ellipsis,
                textAlign: TextAlign.right,
                maxLines: 3,
                style: TextStyle(fontSize: 14, color: Colors.black38),
              ),
              Icon(Icons.arrow_forward_ios, size: 14, color: Colors.black38)
            ],
          )
        ],
      ),
    );
  }
}
